﻿using B.S.XZYData.Infrastructure.Inpement;
using B.S.XZYData.Infrastructure.Interface;
using B.S.XZYData.Infrastructure;
using SqlSugar;
using System.Reflection;
using Yitter.IdGenerator;
using NLog.Web;
using B.S.XZYData.Api.Wrter.AllError;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using B.S.XZYData.Api.Wrter.Common;

namespace B.S.XZYData.Api.Wrter.Extensions
{
    public static class ServicesCollectionExtensions
    {
        public static WebApplicationBuilder Inject(this WebApplicationBuilder builder)
        {
            // Add services to the container.
            //全局异常过滤
            builder.Services.AddControllers(x=>x.Filters.Add<Globalexceptionfilter>());
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            //中文注释
            builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.XZYData.Api.Wrter.xml", true));
            //注册SqlSugar上下文
            builder.Services.AddSqlSugarContext(builder.Configuration.GetConnectionString("db"),
                builder.Environment.IsDevelopment());
            //注册中介者
            builder.Services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //http 上下文
            builder.Services.AddHttpContextAccessor();
            //JWT
            var jwtsettings = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
            //授权认证（使用JWT）
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {
                // 私钥
                var secretByte = Encoding.UTF8.GetBytes(jwtsettings.SigningKey);
                o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = jwtsettings.Issuer,

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = jwtsettings.Audience,

                    // 验证是否过期
                    ValidateLifetime = true,

                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });

            // 配置Swagger
            builder.Services.AddSwaggerGen(o =>
            {
                // 显示 授权信息
                o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
                {
                    Description = "添加JWT授权Token：Bearer Token值",
                    Name = "Authorization",
                    In = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
                    BearerFormat = "JWT",
                    Scheme = "Bearer"
                });
                o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });

                // 避免不同命名空间下同名类导致的 SchemaId 冲突
                o.CustomSchemaIds(type => type.FullName?.Replace(".", "_"));
            });
            //配置Base
            builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            //配置automapper
            builder.Services.AddAutoMapper(typeof(MyAutoMapper));
            //注册雪花id
            YitIdHelper.SetIdGenerator(new IdGeneratorOptions(0));
            //配置日志
            builder.Host.UseNLog();

            return builder;
        }

        public static IServiceCollection AddSqlSugarContext(this IServiceCollection services, string? connectionString, bool enableSqlLog)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("数据库连接字符串不能为空");
            }

            // 配置SqlSugar
            var config = new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType.MySql, // 配置为MySQL
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute
            };

            // 注册SqlSugar客户端
            services.AddSingleton<ISqlSugarClient>(provider =>
            {
                var client = new SqlSugarClient(config);
                
                if (enableSqlLog)
                {
                    client.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine($"SQL: {sql}");
                        Console.WriteLine($"Parameters: {string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value) ?? new string[] { })}");
                    };
                }
                
                return client;
            });

            // 注册数据库上下文
            services.AddScoped<MyDbContext>(provider =>
            {
                return new MyDbContext(config);
            });

            return services;
        }
    }
}
